/**
 * @name axios二次封装
 * 1：实例化
 * 2：（两个拦截：拦截请求，拦截响应）
 * 3：（三个处理：处理token, 处理loading, 处理错误状态）
 */
import { message, Button, Space } from 'antd'
import axios from 'axios'
import NProgress from 'nprogress'
// 1
const instance = axios.create({
  // baseURL: '',
  timeout: 50000, // 过期时间
})

// 2
// 拦截请求
instance.interceptors.request.use(
  (config) => {
    NProgress.start()
    // token
    config.token = window.localStorage.getItem('token')
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    NProgress.done()
    // 处理返回数据结构
    return response.data
  },
  (error) => {
    // 401 Unauthorized
    // 404 	Not Found
    // 403 Forbidden
    // 500 	Internal Server Error
    let status = error.response.status
    let message = ''
    switch (status) {
      case 401:
        message = 'Unauthorized'
        break
      case 403:
        message = 'Forbidden'
        break
      case 404:
        message = 'Not Found'
        break
      case 500:
        message = 'Internal Server Error'
        break
      default:
        console.log('error')
    }
    message.error(message)
    return Promise.reject(message)
    // 状态码 200 300 400 -401-404 500
  }
)

export default instance
